<?php
/**
 * SCRIPT_NAME: AdminRule.php
 * Created by PhpStorm.
 * Time: 2016/3/18 21:10
 * FUNCTION:
 * @author: Doogie <461960962@qq.com>
 */

namespace app\admin\controller;

use app\common\library\Tree;
use think\Request;
use think\Response;

class AdminAuth extends Base{

    public function __construct() {
        parent::__construct();
    }

    public function index(Request $request){
        if($request->isGet()){
            return $this->fetch();
        }
        //搜索
        $keyword = $request->param('keyword', '');

        $ruleList =  model('AdminAuth')->where('id','like',"'%".$keyword."%'")
            ->whereOr('title','like','%'.$keyword.'%')
            ->order('sort asc')->select();

        $tree = new Tree();
        $list = $tree->toFormatTree($ruleList);
        return json([
            "rows"  =>  $list,
            "total" =>  count($list)
        ]);
    }

    /**
     * 编辑和新增
     * @param Request $request
     * @return Response|void
     */
    public function editAuth(Request $request){
        if($request->isPost()){

            if( $id = $request->post("id")){
                $state  =  model('AdminAuth')->validate('AdminAuth.edit')->save($request->post(),[ "id" => $id]);
            }else{
                $rule_info = $request->post();
                $rule_info['create_time'] = time();
                $state  =  model('AdminAuth')->validate('AdminAuth.add')->save($rule_info);
            }

            return $state ? $this->success("保存成功!") : $this->error(model('AdminAuth')->getError());
        }else{
            $id = $request->param('id');
            $ruleItem =  model('AdminAuth')->get($id);
            $this->assign('ruleItem',$ruleItem);
            $this->assign([
                'meta_title' => '编辑角色权限',
                'post_url' => url('edit'),
                'type_list' =>  model('AdminAuth')->types(),
                'rule_tree' => select_list_as_tree('AdminAuth', ['status'=>1], '顶部菜单')
            ]);
            return new Response($this->fetch() , 200);
        }
    }

    /**
     * 删除功能
     * @param Request $request
     */
    public function delete(Request $request){
        $id = $request->param('id');
        if( !empty($id)){
            $rule_count = model('AdminAuth')->where(array('pid'=>$id))
                ->count();
            if($rule_count > 0){
                return $this->error('存在子菜单，不允许删除!');
            }
            $rule_info = model('AdminAuth')->get($id);
            $rule_info->delete();
        }
        return $this->success('删除成功!');
    }
}